﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace Dashboard.ProductBonus.Common
{
    public static class PagedDataTable
    {
        /// <summary>
        /// DataTable分页
        /// </summary>
        /// <param name="dataTable">DataTable</param>
        /// <param name="pageIndex">页索引,注意：从1开始</param>
        /// <param name="pageSize">每页大小</param>
        /// <returns></returns>
        public static DataTable GetPagedTable(DataTable dataTable, int pageIndex, int pageSize)
        {
            if (pageIndex == 0)
                return dataTable;
            DataTable newdt = dataTable.Copy();
            newdt.Clear();

            int rowbegin = (pageIndex - 1) * pageSize;
            int rowend = pageIndex * pageSize;

            if (rowbegin >= dataTable.Rows.Count)
                return newdt;

            if (rowend > dataTable.Rows.Count)
                rowend = dataTable.Rows.Count;
            for (int i = rowbegin; i <= rowend - 1; i++)
            {
                DataRow newdr = newdt.NewRow();
                DataRow dr = dataTable.Rows[i];
                foreach (DataColumn column in dataTable.Columns)
                {
                    newdr[column.ColumnName] = dr[column.ColumnName];
                }
                newdt.Rows.Add(newdr);
            }

            return newdt;
        }
    }
}
